package com.example.demo.controller;


import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.example.demo.controller.ResourceLoader;
import com.lowagie.text.pdf.BaseFont;

import freemarker.template.TemplateException;


public class PdfDocumentGenerator {
//    private final static Logger logger = Logger.getLogger(PdfDocumentGenerator.class);

    private final static Html htmlGenerator;
    static {
        htmlGenerator = new Html();
    }


    /*
     *
     * 根据html的内容生成pdf
     *
     */
    public static void pdfgenerate(String htmlContent, String outputFile)throws Exception{
        OutputStream out = null;

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(htmlContent.getBytes("UTF-8")));
        ITextRenderer iTextRenderer = new ITextRenderer();
        // classpath 路径
        String outputFileClass = ResourceLoader.getPath("");
        //添加字体，以支持中文
        iTextRenderer.getFontResolver().addFont(outputFileClass+"fronts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        iTextRenderer.getFontResolver().addFont(outputFileClass+"fronts/SIMSUN.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        File f = new File(outputFile);
        if (f != null && !f.getParentFile().exists()) {
            f.getParentFile().mkdir();
        }
        out = new FileOutputStream(outputFile);
        iTextRenderer.setDocument(doc, null);
        iTextRenderer.layout();
        iTextRenderer.createPDF(out);
        out.close();
    }

    /*
     *
     * 对上面的方法再进行封装
     *
     */
    public boolean generate(String template, Map<String,Object> variables,String outputFile) throws IOException, TemplateException{

        String htmlContent = this.htmlGenerator.generate(template,variables);
        System.out.println("+++++++++"+htmlContent);//打印出html 的内容方便查看是否是html 的时候已经出现乱码
        try {
            this.pdfgenerate(htmlContent, outputFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}

